<?php

namespace doumiaoduo\aliyun;

use common\components\helpers\Fun;
use yii\helpers\Html;
use yii\widgets\InputWidget;

class ImageConfig extends InputWidget
{

    public $clientOptions = [];

    public $serverParam = [];

    public $buttonOptions = [];

    public $phoneOptions = [];

    public $view;
    public $asset;

    public function init()
    {
        parent::init();
        $this->clientOptions['csrf-param'] = \Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token'] = \Yii::$app->request->getCsrfToken();
        $this->buttonOptions['id'] = isset($this->buttonOptions['id']) ? $this->buttonOptions['id'] : "image_config_{$this->options['id']}";
        if (isset($this->clientOptions['serverUrl'])) {
            $this->clientOptions['serverUrl'] = str_replace('action', 'uploadimage', $this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl'] = str_replace(urlencode('action'), 'uploadimage', $this->clientOptions['serverUrl']);
        }
        $this->clientOptions['serverwaterUrl'] = str_replace('uploadimage', 'uploadwatermark', $this->clientOptions['serverUrl']);
    }


    public function run()
    {
        $id = str_replace('-', '_', $this->options['id']);
        $strHtml = '';
        if ($this->hasModel()) {
            $strHtml .= Html::activeHiddenInput($this->model, $this->attribute, $this->options);
        } else {
            $strHtml .= Html::hiddenInput($this->name, $this->value, $this->options);
        }
        $this->view = $this->getView();
        $this->asset = ImageConfigAsset::register($this->view);
        $this->registerClientScript();
        $imageconfigviewfile = dirname(\Yii::$app->basePath).DIRECTORY_SEPARATOR.'common'.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'services'.DIRECTORY_SEPARATOR.'imageconfig'.DIRECTORY_SEPARATOR.'imageconfigview.php';

        $addfilelogo = $this->asset->baseUrl.DIRECTORY_SEPARATOR.'plusadd.png';
        $strHtml .= $this->renderFile($imageconfigviewfile,['id'=>$id,'addfilelogo'=>$addfilelogo]);
        echo $strHtml;

    }

    public function registerClientScript()
    {
        $currenturl = \Yii::$app->request->getHostInfo() . \Yii::$app->request->url;
        $current_action = \Yii::$app->controller->action->id;
        $getwaterlisturl = str_replace($current_action, "watermarklist", $currenturl);
        $id = str_replace('-', '_', $this->options['id']);
        $js = '';
        $js .= <<<JS

        $("input[name='watertype_{$id}']").click(function(){
            var watertypeval = $(this).val();
            if(watertypeval=='wenzi'){
                $('.watermark-content_{$id}').show();
                $('.watermark-content_{$id} .watermark-image-set').hide();
                $('.watermark-content_{$id} .watermark-text-set').show();
            }else if(watertypeval=='tupian'){
                $('.watermark-content_{$id}').show();
                $('.watermark-content_{$id} .watermark-text-set').hide();
                $('.watermark-content_{$id} .watermark-image-set').show();
            }else{
                $('.watermark-content_{$id}').hide();
            }
        });
        $('.easyui-linkbutton').click(function(){

			using(['window'], function(){
				$('#dd').dialog({
					title:'Dialog',
					width:300,
					height:200
				});
			});
        });
        $('#watermark_choose_{$id}').click(function(){
            getWaterImgList("{$getwaterlisturl}");
            var uploadera = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // 文件接收服务端。
            swf: '{$this->asset->baseUrl}/webuploader/Uploader.swf',
            server: '{$this->clientOptions['serverwaterUrl']}',
            // 选择文件的按钮。可选。// 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick:'#waterimgappend2',
            fileVal: 'waterfileInput',
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            resize: false,
          });
                      /**uploadera.addButton({
                        id: '#waterimgappend1',
                    });*/
         uploadera.on('uploadBeforeSend', function( block, data, headers) {//文件上传前添加参数
            $.extend(data, {'{$this->clientOptions['csrf-param']}': '{$this->clientOptions['csrf-token']}',});
            });
         uploadera.on( 'uploadSuccess', function( file,response) {
            var newwaterimg = "<input type='radio' name='waterimgs' value='watermarks/"+response.title+"'/><img src='"+response.imgprocessurl+"'/>&nbsp;&nbsp;&nbsp;";
            $('#waterimages').append(newwaterimg);
         });
         uploadera.on( 'uploadError', function( file ) {
            alert('失败');
         });
            return false;
        });
        $('#confirmconfig_{$id}').click(function(){
            var configtext = '';
            var width = $('#watermark_width_{$id}').val();
            if(width!=''&&width>0){
                configtext += "w|"+width+",";
            }
            var height = $('#watermark_height_{$id}').val();
            if(height!=''&&height>0){
                configtext += "h|"+height+",";
            }
            var watertypeval = $("input[name='watertype_{$id}']").filter(':checked').val();
            var transparency = $('#transparency_{$id}').val();
            var pos = $("select[name='watermarkpos_{$id}']").val();
            if(watertypeval == 'wenzi'){
                var wenzi = $('#watermark_text_{$id}').val();
                configtext += "water_pos|"+pos+",water_text|"+wenzi+",water_transparency|"+transparency;
                $('#{$this->options['id']}').val(configtext);
            }else if(watertypeval == 'tupian'){
                var imageurl = $('#watermark_url_{$id}').val();
                configtext += "water_pos|"+pos+",water_img|"+imageurl+",water_transparency|"+transparency;
                $('#{$this->options['id']}').val(configtext);
            }else{
                $('#{$this->options['id']}').val(configtext);
            }
            alert('图片配置完成');
        });

        function getWaterImgList(url){
            $.ajax({
                type: "POST",
                url: url,
                cache: false,
                async: false,
                dataType: "json",
                success: function(msg){
                 var waterimglist = "";
                     $.each(eval(msg),function(idx,item){
                           waterimglist = waterimglist + "<input type='radio' name='waterimgs' value='"+item.key+"'/><img src='"+item.url+"'/>&nbsp;&nbsp;&nbsp;";
                     });
                     $('#waterimages').empty();
                     $('#waterimages').append(waterimglist);
                      $('#choosewaterover').show();
                     /*$('.waterimglistdiv').show();*/
                      $('#bg').show();
                      $('#waterimglistdiv').show();
                      $('#closewaterimg').on('click',function(){
                        $('#bg').hide();
                        $('#waterimglistdiv').hide();
                        $('#choosewaterover').hide();
                        return false;
                      });
                      $('#waterimgconfirm').on('click',function(){
                        //var watervalue = $("input[name='waterimgs']").filter(':checked').next('img').attr("src");
                        var watervalue = $("input[name='waterimgs']").filter(':checked').val();
                        if(watervalue==null||watervalue==''){
                            alert('请选择水印图片');
                            return false;
                        }else{
                            watervalue = watervalue+'@20P';
                            $('#watermark_url_{$id}').val(watervalue);
                            $('#bg').hide();
                            $('#waterimglistdiv').hide();
                            $('#choosewaterover').hide();
                            return false;
                        }
                });


                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert(XMLHttpRequest.status);
                    alert(XMLHttpRequest.readyState);
                    alert(textStatus);
                }
            });
            return false;
        }

        $(".close").click(function () {
        $("#bg,#waterimglistdiv").css("display", "none");
        });
JS;


        $this->view->registerJs($js);

    }
}